<template>
    <div class="head">
        <div class="left">
            <i class="el-icon-s-fold" @click="$emit('valeuChange',true)" v-if="!valeu"></i>
            <i class="el-icon-s-unfold" @click="$emit('valeuChange',false)" v-else></i>
            <cBreadcrumb />
        </div>
        <div class="right">
            <screenfull style="margin-right:10px" />
            <el-dropdown trigger="click" size="medium" @command="changeSize">
                <span class="el-dropdown-link">
                    <i class="iconfont icon-size"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command='default' :disabled="size==='default'">default</el-dropdown-item>
                    <el-dropdown-item command="medium" :disabled="size==='medium'">medium</el-dropdown-item>
                    <el-dropdown-item :command="null" :disabled="size===null">small</el-dropdown-item>
                    <el-dropdown-item command="mini" :disabled="size==='mini'">mini</el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>

            <div class="theme">
                <i class="el-icon-sunny" @click="switchTheme('dark')" v-if="theme==='light'"></i>
                <i class="el-icon-moon" @click="switchTheme('light')" v-else></i>
            </div>

            <!-- <el-color-picker v-model="themeColor" :predefine="['#409EFF', '#1890ff', '#304156','#212121','#11a983', '#13c2c2', '#6959CD', '#f5222d', ]"
                class="theme-picker" popper-class="theme-picker-dropdown" />-->
            <img :src="userInfo.avatar" alt="">
            <el-dropdown trigger="click" @command="handleCommand">
                <span class="el-dropdown-link">
                    {{userInfo.username}}<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item :command="1">首页</el-dropdown-item>
                    <el-dropdown-item :command="2">退出登录</el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>
        </div>
    </div>
</template>

<script>
import cBreadcrumb from "./cBreadcrumb.vue";
import screenfull from "@/components/Screenfull/index";
import { mapMutations, mapState } from "vuex";
import { removeStore } from "@/common/util";

import variables from "@/style/element-variables.scss";

const version = require("element-ui/package.json").version; // element-ui version from node_modules
const ORIGINAL_THEME = "#409EFF"; // default color

import { initTheme } from "@/style/theme.js"
import { lightTheme, darkTheme } from "@/style/variable.js";
export default {
    components: { cBreadcrumb, screenfull },
    props: {
        valeu: {
            type: Boolean,
            default: false,
        },
    },
    data () {
        return {
            chalk: "", // content of theme-chalk css
            // themeColor: "",
        };
    },
    // created () {
    // console.log(this.theme);
    // this.themeColor = this.theme || variables.theme;
    // },
    model: {
        prop: "valeu",
        event: "valeuChange",
    },
    methods: {
        switchTheme (theme) {
            initTheme(theme)
            this.SET_THEME(theme)
        },
        handleCommand (type) {
            switch (type) {
                case 1:
                    this.push("/");
                    break;
                case 2:
                    const loading = this.$loading({
                        lock: true,
                        text: "loading",
                        spinner: "el-icon-loading",
                        background: "rgba(0, 0, 0, 0.7)",
                    });
                    removeStore("userInfo");
                    removeStore("authorityList");
                    setTimeout(() => {
                        location.reload();
                        loading.close();
                    }, 1000);
                    break;
            }
        },
        changeSize (type) {
            this.$ELEMENT.size = type;
            this.SET_SIZE(type);
            this.$router.go(0);
        },
        updateStyle (style, oldCluster, newCluster) {
            let newStyle = style;
            oldCluster.forEach((color, index) => {
                newStyle = newStyle.replace(
                    new RegExp(color, "ig"),
                    newCluster[index]
                );
            });
            return newStyle;
        },

        getCSSString (url, variable) {
            return new Promise((resolve) => {
                const xhr = new XMLHttpRequest();
                xhr.onreadystatechange = () => {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        this[variable] = xhr.responseText.replace(
                            /@font-face{[^}]+}/, "");
                        resolve();
                    }
                };
                xhr.open("GET", url);
                xhr.send();
            });
        },

        getThemeCluster (theme) {
            const tintColor = (color, tint) => {
                let red = parseInt(color.slice(0, 2), 16);
                let green = parseInt(color.slice(2, 4), 16);
                let blue = parseInt(color.slice(4, 6), 16);

                if (tint === 0) {
                    // when primary color is in its rgb space
                    return [red, green, blue].join(",");
                } else {
                    red += Math.round(tint * (255 - red));
                    green += Math.round(tint * (255 - green));
                    blue += Math.round(tint * (255 - blue));

                    red = red.toString(16);
                    green = green.toString(16);
                    blue = blue.toString(16);

                    return `#${red}${green}${blue}`;
                }
            };

            const shadeColor = (color, shade) => {
                let red = parseInt(color.slice(0, 2), 16);
                let green = parseInt(color.slice(2, 4), 16);
                let blue = parseInt(color.slice(4, 6), 16);

                red = Math.round((1 - shade) * red);
                green = Math.round((1 - shade) * green);
                blue = Math.round((1 - shade) * blue);

                red = red.toString(16);
                green = green.toString(16);
                blue = blue.toString(16);

                return `#${red}${green}${blue}`;
            };

            const clusters = [theme];
            for (let i = 0; i <= 9; i++) {
                clusters.push(tintColor(theme, Number((i / 10).toFixed(2))));
            }
            clusters.push(shadeColor(theme, 0.1));
            return clusters;
        },
        ...mapMutations(["SET_SIZE", "SET_THEME"]),
    },
    watch: {
        theme: {
            async handler (theme) {
                console.log(lightTheme['--color-primary-1']);

                let val = theme === 'light' ? lightTheme['--color-primary-1'] : darkTheme['--color-primary-1']
                const oldVal = val;
                if (typeof val !== "string") return;
                const themeCluster = this.getThemeCluster(val.replace("#", ""));
                const originalCluster = this.getThemeCluster(
                    oldVal.replace("#", "")
                );
                const $message = this.$message({
                    message: "  Compiling the theme",
                    customClass: "theme-message",
                    type: "success",
                    duration: 0,
                    iconClass: "el-icon-loading",
                });
                const getHandler = (variable, id) => {
                    return () => {
                        const originalCluster = this.getThemeCluster(
                            ORIGINAL_THEME.replace("#", "")
                        );
                        const newStyle = this.updateStyle(
                            this[variable],
                            originalCluster,
                            themeCluster
                        );

                        let styleTag = document.getElementById(id);
                        if (!styleTag) {
                            styleTag = document.createElement("style");
                            styleTag.setAttribute("id", id);
                            document.head.appendChild(styleTag);
                        }
                        styleTag.innerText = newStyle;
                    };
                };

                if (!this.chalk) {
                    const url = `https://unpkg.com/element-ui@${version}/lib/theme-chalk/index.css`;
                    await this.getCSSString(url, "chalk");
                }

                const chalkHandler = getHandler("chalk", "chalk-style");

                chalkHandler();

                const styles = [].slice
                    .call(document.querySelectorAll("style"))
                    .filter((style) => {
                        const text = style.innerText;
                        return (
                            new RegExp(oldVal, "i").test(text) &&
                            !/Chalk Variables/.test(text)
                        );
                    });
                styles.forEach((style) => {
                    const { innerText } = style;
                    if (typeof innerText !== "string") return;
                    style.innerText = this.updateStyle(
                        innerText,
                        originalCluster,
                        themeCluster
                    );
                });

                // this.$emit("change", val);
                // this.SET_THEME(val);
                $message.close();
            },
            immediate: true
        }
    },
    computed: {
        ...mapState("user", ["userInfo"]),
        ...mapState(["size", "theme"]),
    },
};
</script>

<style lang="scss" scoped>
.head {
    width: 100%;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .left {
        display: flex;
        align-items: center;
        & > i {
            font-size: 24px;
            color: var(--color-text-2);
        }
    }
    .right {
        padding-right: 15px;
        display: flex;
        align-items: center;
        & > img {
            width: 35px;
            height: 35px;
            border-radius: 50%;
            margin: 0 10px;
        }
        .el-dropdown-link {
            cursor: pointer;
        }
        .iconfont {
            cursor: pointer;
        }
        .theme-picker {
            margin-left: 15px;
        }
    }
    .theme {
        font-size: 20px;
        margin-left: 8px;
        cursor: pointer;
        .el-icon-moon {
            font-weight: bold;
        }
        .el-icon-sunny {
            font-weight: bold;
        }
    }
    ::v-deep .el-dropdown {
        color: var(--color-text-1);
    }
}
</style>